<template>
  <div>
    定位页面
    <input type="text" v-model="iptVal" />
    <ul>
      <li v-for="item in list" :key="item.id" @click="uptCtiy(item)">
        {{ item.name }}
      </li>
    </ul>
    <div id="container"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      iptVal: "",
      list: [],
    };
  },
  computed: {
    ...mapState(["currentCity"]), // this.$store.state.currentCity
  },
  watch: {
    iptVal() {
      var _this = this;
      AMap.plugin("AMap.Autocomplete", function () {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市，默认全国
          city: _this.currentCity,
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(_this.iptVal, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(status, result);
          _this.list = result.tips;
        });
      });
    },
  },
  created() {},
  mounted() {
    if (this.$store.state.currentSelected.name) {
      var info = this.$store.state.currentSelected;
      var map = new AMap.Map("container", {
        zoom: 15, //级别
        center: [info.location.lng, info.location.lat],
      });
      var marker = new AMap.Marker({
        position: [info.location.lng, info.location.lat], //位置
      });
      map.add(marker); //添加到地图
    } else {
      var map = new AMap.Map("container", {
        resizeEnable: true,
      });
    }
  },
  methods: {
    uptCtiy(val) {
      this.$store.commit("uptCurrentSelected", val);
      this.$router.push("/home");
    },
  },
};
</script>

<style scoped lang="scss">
#container {
  width: 300px;
  height: 180px;
}
</style>
